/*
 * Copyright 2009 Johnson Consulting Services
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * 
 */
package com.johnsoncs.gwt.widgets.samples.client;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.widgetideas.client.ProgressBar;
import com.johnsoncs.gwt.widgets.client.common.LightBox;
import com.johnsoncs.gwt.widgets.client.util.Callback;
import com.johnsoncs.gwt.widgets.samples.client.mock.DbInitStatus;
import com.johnsoncs.gwt.widgets.samples.client.mock.MockRemoteTableModel;

/**
 * @author wilj
 *
 */
public class DbStatusDialog {
	private LightBox box = null;
	private final Callback<Boolean> callback;
	private final ProgressBar progress = new ProgressBar(0, 100, 0);

	public DbStatusDialog(final Callback<Boolean> callback) {
		this.callback = callback;
	}

	public void check() {
		checkInitStatus();
	}

	private void checkInitStatus() {
		MockRemoteTableModel.Util.getService().getInitStatus(new AsyncCallback<DbInitStatus>() {
			@Override
			public void onFailure(final Throwable cause) {
				callback.exec(false);
				throw new RuntimeException("Error checking db init status", cause);
			}

			@Override
			public void onSuccess(final DbInitStatus result) {
				if (result.isInitialized()) {
					if (box != null) {
						box.hide();
						box = null;
					}
					callback.exec(true);
				} else {
					if (box == null) {
						box = new LightBox(RootPanel.get());
						final VerticalPanel panel = new VerticalPanel();
						panel.add(new Label("Database is initializing"));
						panel.add(progress);
						box.setWidget(panel);
						box.show();
					}
					progress.setProgress(result.getPercentComplete());

					new Timer() {
						@Override
						public void run() {
							checkInitStatus();
						}
					}.schedule(3000);
				}
			}
		});
	}
}
